// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.inventory.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.inventory.entity.InventoryBatchNo;
import com.fowo.api.inventory.mapper.InventoryBatchNoMapper;
import com.fowo.api.inventory.model.InventoryBatchNoExcelPo;
import com.fowo.api.inventory.model.InventoryBatchNoImportPo;
import com.fowo.api.inventory.model.InventoryBatchNoItemVo;
import com.fowo.api.inventory.model.InventoryBatchNoSearchParamPo;
import com.fowo.api.inventory.model.InventoryBatchNoVo;
import com.fowo.api.inventory.service.InventoryBatchNoService;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 批次即时库存表 服务实现类
 * @author 蜂窝蜜造平台 配置人：吴天洋
 */
@Service
@Slf4j
@DS("ds23")
public class InventoryBatchNoServiceImpl
  extends ServiceImpl<InventoryBatchNoMapper, InventoryBatchNo>
  implements InventoryBatchNoService {

  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>();
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  protected Validator validator;

  /**
   * 创建批次即时库存表
   * @param model 批次即时库存表
   * @return 新数据的主键
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(InventoryBatchNoVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    InventoryBatchNo entity = new InventoryBatchNo();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }

    if (model.getVersion() == null) {
      entity.setVersion(0);
    }
    if (this.save(entity)) {
      return entity.getId();
    }
    throw new Exception("批次即时库存表保存失败");
  }

  /**
   * 更新批次即时库存表
   * @param model 批次即时库存表
   * @return 更新是否成功
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(InventoryBatchNoVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    InventoryBatchNo entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("批次即时库存表不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "createTime",
      "createUser",
      "lastUpdateTime",
      "lastUpdateUser"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      return true;
    }
    return false;
  }/**
   * 更新批次即时库存表（带空值）
   * @param model 批次即时库存表
   * @return 更新是否成功
   */

  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(InventoryBatchNoVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    InventoryBatchNo entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("批次即时库存表不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(InventoryBatchNo::getLastUpdateTime, model.getLastUpdateTime())
      .set(InventoryBatchNo::getLastUpdateUser, model.getLastUpdateUser())
      .set(InventoryBatchNo::getStockId, model.getStockId())
      .set(InventoryBatchNo::getProjectId, model.getProjectId())
      .set(InventoryBatchNo::getItemId, model.getItemId())
      .set(InventoryBatchNo::getBatchNo, model.getBatchNo())
      .set(InventoryBatchNo::getShelfLife, model.getShelfLife())
      .set(InventoryBatchNo::getProductionDate, model.getProductionDate())
      .set(InventoryBatchNo::getExpiryDate, model.getExpiryDate())
      .set(InventoryBatchNo::getStockQty, model.getStockQty())
      .set(InventoryBatchNo::getStockAmount, model.getStockAmount())
      .set(InventoryBatchNo::getAuxId, model.getAuxId())
      .set(InventoryBatchNo::getAuxQty, model.getAuxQty())
      .set(InventoryBatchNo::getLockQty, model.getLockQty())
      .set(InventoryBatchNo::getDisplayQty, model.getDisplayQty())
      .set(InventoryBatchNo::getDefectQty, model.getDefectQty())
      .set(InventoryBatchNo::getWayQty, model.getWayQty())
      .set(InventoryBatchNo::getVersion, model.getVersion())
      .set(InventoryBatchNo::getOrgId, model.getOrgId())
      .set(InventoryBatchNo::getShopId, model.getShopId())
      .set(InventoryBatchNo::getFnSku, model.getFnSku())
      .set(InventoryBatchNo::getAvailableQty, model.getAvailableQty())
      .eq(InventoryBatchNo::getId, model.getId())
      .update();
    if (isOk) {}
    return isOk;
  }

  /**
   * 删除批次即时库存表
   * @param id 批次即时库存表的主键
   * @return 删除是否成功
   */
  @Override
  public boolean delete(Long id) throws Exception {
    return this.removeById(id);
  }

  /**
   * 批量删除批次即时库存表
   * @param ids 批次即时库存表的主键列表
   * @return 删除是否成功
   */
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    return baseMapper.deleteBatchIds(ids) > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<InventoryBatchNoImportPo> excelToImportRow(
    InventoryBatchNoImportPo row,
    Integer rowNumber,
    InventoryBatchNoVo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<InventoryBatchNoImportPo> ir = new ImportRow<InventoryBatchNoImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<InventoryBatchNoImportPo>> validate = validator.validate(
      row
    );
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new InventoryBatchNoVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, InventoryBatchNoImportPo.class);

    // 一般数据处理
    vo.setStockId(SheetUtils.tryToLong(row.getStockId()));
    vo.setProjectId(SheetUtils.tryToLong(row.getProjectId()));
    vo.setItemId(SheetUtils.tryToLong(row.getItemId()));
    vo.setShelfLife(SheetUtils.tryToInteger(row.getShelfLife()));
    vo.setProductionDate(SheetUtils.tryToDateTime(row.getProductionDate()));
    vo.setExpiryDate(SheetUtils.tryToDateTime(row.getExpiryDate()));
    vo.setStockQty(SheetUtils.tryToDecimal(row.getStockQty()));
    vo.setStockAmount(SheetUtils.tryToDecimal(row.getStockAmount()));
    vo.setAuxId(SheetUtils.tryToInteger(row.getAuxId()));
    vo.setAuxQty(SheetUtils.tryToDecimal(row.getAuxQty()));
    vo.setLockQty(SheetUtils.tryToDecimal(row.getLockQty()));
    vo.setDisplayQty(SheetUtils.tryToDecimal(row.getDisplayQty()));
    vo.setDefectQty(SheetUtils.tryToDecimal(row.getDefectQty()));
    vo.setWayQty(SheetUtils.tryToDecimal(row.getWayQty()));
    vo.setVersion(SheetUtils.tryToInteger(row.getVersion()));
    vo.setOrgId(SheetUtils.tryToInteger(row.getOrgId()));
    vo.setAvailableQty(SheetUtils.tryToDecimal(row.getAvailableQty()));

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<InventoryBatchNoImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<InventoryBatchNoImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            InventoryBatchNoImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(
              InventoryBatchNoImportPo row,
              AnalysisContext cxt
            ) {
              InventoryBatchNoVo vo = new InventoryBatchNoVo();
              ImportRow<InventoryBatchNoImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                vo,
                variables,
                allowOverrides
              );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(List<ImportRow<InventoryBatchNoImportPo>> rows)
    throws Exception {
    List<Long> importedIdList = new ArrayList<>();
    Map<String, Object> variables = new HashMap<>();
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<InventoryBatchNoImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      InventoryBatchNoVo vo = new InventoryBatchNoVo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        update(vo);
        importedIdList.add(vo.getId());
      }
    }
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @Override
  public void export(
    Long templateId,
    InventoryBatchNoSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions = new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<InventoryBatchNoExcelPo> items = new ArrayList<InventoryBatchNoExcelPo>();
    while (true) {
      search.setCurrent(current);
      Page<InventoryBatchNoItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<InventoryBatchNoItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (InventoryBatchNoItemVo item : list) {
        InventoryBatchNoExcelPo excel = new InventoryBatchNoExcelPo();
        BeanUtils.copyProperties(item, excel);

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "批次即时库存表(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .sheet()
      .head(InventoryBatchNoExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过批号查询批次即时库存表主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByBatchNo(String batchNo) {
    return this.baseMapper.getIdByBatchNo(batchNo);
  }

  /**
   * 通过批号查询批次即时库存表多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByBatchNo(List<String> list) {
    return this.baseMapper.getIdsByBatchNo(list);
  }

  /**
   * 通过批次即时库存表主键查询批号
   */
  @Override
  public String getBatchNoById(Long id) {
    return this.baseMapper.getBatchNoById(id);
  }

  /**
   * 通过批次即时库存表主键查询批号列表
   */
  @Override
  public List<String> getBatchNoByIds(List<Long> ids) {
    return this.baseMapper.getBatchNoByIds(ids);
  }

  /**
   * 获取详情
   * @param id 批次即时库存表的主键
   */
  @Override
  public InventoryBatchNoVo getVoById(Long id) throws Exception {
    InventoryBatchNoVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }
    return vo;
  }

  /**
   * 分页查询批次即时库存表
   * @param search 查询条件
   * @return 批次即时库存表分页查询结果
   */
  @Override
  public Page<InventoryBatchNoItemVo> pageSearch(
    InventoryBatchNoSearchParamPo search
  ) {
    Page<InventoryBatchNoItemVo> page = new Page<>();
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    return page;
  }

  /**
   * 批次即时库存表快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'InventoryBatchNoOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<InventoryBatchNoItemVo>> searchOptions(
    InventoryBatchNoSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询批次即时库存表
   * @param search 查询条件
   * @return 批次即时库存表列表查询结果
   */
  @Override
  public List<InventoryBatchNoItemVo> search(
    InventoryBatchNoSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询批次即时库存表最后更新时间
   * @param search 查询条件
   * @return 批次即时库存表最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(InventoryBatchNoSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  @Override
  public InventoryBatchNo getOne(LambdaQueryWrapper<InventoryBatchNo> queryWrapper) {
    return this.getOne(queryWrapper,false);
  }

  @Override
  public void saveBatch(List<InventoryBatchNo> inventoryBatchNo) {
    this.saveOrUpdateBatch(inventoryBatchNo);
  }

  @Override
  public boolean updateBatch(List<InventoryBatchNo> updateInventoryBatchNoList) {
   return this.updateBatchById(updateInventoryBatchNoList);
  }
}
